﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using uTrade.Data.Stock;

namespace uTrade.Data
{
    internal class StockFinanceInfoService
    {
        private static readonly List<int> ALLlistCon = new List<int>();
        private static readonly List<int> OverlistCon = new List<int>();
        private readonly Server m_Server;
        private StringBuilder Result = new StringBuilder(1024 * 1024);
        private StringBuilder ErrInfo = new StringBuilder(256);

        public StockFinanceInfoService()
        { }

        public StockFinanceInfoService(Server oServer)
        {
            m_Server = oServer;
        }

        public void DataAccess()
        {
            bool bool1 = TdxApi.OpenTdx(ErrInfo);
            int ConnectionID = TdxApi.TdxHq_Multi_Connect(m_Server.IP, m_Server.Port, Result, ErrInfo);
            OverlistCon.Add(ConnectionID);
            int conSZ = OverlistCon[0];
            OverlistCon.RemoveAt(0);

            bool1 = TdxApi.TdxHq_Multi_GetFinanceInfo(ConnectionID, 0, "000002", Result, ErrInfo);
            Console.WriteLine(bool1 ? Result.ToString() : ErrInfo.ToString());

            StockFinanceInfoManager.Clear();
            Thread tdStock5MinInfo = new Thread(SyncStocFinanceInfo);
            tdStock5MinInfo.Start();
        }

        private void SyncStocFinanceInfo()
        {
            //IsFinanceWork = true;
            int ConnectionID = TdxApi.TdxHq_Multi_Connect("222.73.49.4", 7709, Result, ErrInfo);
            ALLlistCon.Add(ConnectionID);
            OverlistCon.Add(ConnectionID);

            List<StockInfo> stockList = StockInfoManager.GetStockCodeList("");

            Dictionary<string, string> Message = new Dictionary<string, string>
            {
                { "Result", "" },
                { "ErrInfo", "" }
            };
            bool bool1;

            #region foreach

            foreach (StockInfo s in stockList)
            {
                //try
                //{
                bool1 = TdxApi.TdxHq_Multi_GetFinanceInfo(ConnectionID, Convert.ToByte(s.Type), s.Symbol, Result, ErrInfo);
                ///出错
                if (!bool1 || Result.ToString() == "")
                {
                    //记录日志
                    continue;
                }
                string[] strRow = Result.ToString().Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);   //分解行的字符串
                string[] strColX = strRow[1].Split("\t".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                //Console.WriteLine(Result.ToString());
                for (int i = 1; i < strRow.Length; i++)
                {
                    string[] strCol = strRow[i].Split("\t".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    if (!(strCol[5].Replace("--", "-") != "0" && strCol[6].Replace("--", "-") != "0"))
                    {
                        continue;
                    }
                    int IsHave = StockFinanceInfoManager.GetRecordCount("Symbol='" + s.Symbol + "' and CWUpdateTime=CONVERT(datetime,'" + strCol[5].Replace("--", "-") + "',102)");
                    if (IsHave > 0)
                    {
                        continue;
                    }
                    StockFinanceInfo stock = new StockFinanceInfo
                    {
                        Type = strCol[0],
                        Symbol = strCol[1],
                        GBLT = strCol[2],
                        SSSF = strCol[3],
                        SSHY = strCol[4],
                        CWUpdateTime = DateTime.ParseExact(strCol[5], "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture),
                        ListingDate = DateTime.ParseExact(strCol[6], "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture),
                        AllGB = strCol[7],
                        GJG = strCol[8],
                        FQRFRG = strCol[9],
                        FRG = strCol[10],
                        BG = strCol[11],
                        HG = strCol[12],
                        ZhGG = strCol[13],
                        AllZC = strCol[14],
                        LDZC = strCol[15],
                        GDZC = strCol[16],
                        WXZC = strCol[17],
                        GDRS = strCol[18],
                        LDFZ = strCol[19],
                        CQFZ = strCol[20],
                        ZBGJJ = strCol[21],
                        JZC = strCol[22],
                        ZYSR = strCol[23],
                        ZYLR = strCol[24],
                        YSZK = strCol[25],
                        YYLR = strCol[26],
                        TZSY = strCol[27],
                        JYXJL = strCol[28],
                        ZXJL = strCol[29],
                        CH = strCol[20],
                        LRZE = strCol[31],
                        SHLR = strCol[32],
                        JLR = strCol[33],
                        WFLR = strCol[34],
                        Unknow1 = strCol[35],
                        Unknow2 = strCol[36]
                    };
                    int ID = StockFinanceInfoManager.Add(stock);
                    if (ID > 0)
                    {
                        string message = "Current tiem is: " + s.Symbol + " type:" + s.Type;
                        //ReportProgress 方法把信息传递给 ProcessChanged 事件处理函数。
                        //第一个参数类型为 int，表示执行进度。
                        //如果有更多的信息需要传递，可以使用 ReportProgress 的第二个参数。
                        //这里我们给第二个参数传进去一条消息。
                        Message["Result"] = Result.ToString();
                        Message["ErrInfo"] = ErrInfo.ToString();
                        Message["Message"] = message.ToString();
                        //bk_FinanceInfo.ReportProgress(i, Message);
                    }
                    else
                    {
                        //记录日志
                        Message["Result"] = Result.ToString();
                        Message["ErrInfo"] = ErrInfo.ToString();
                        Message["Message"] = "";
                        //bk_FinanceInfo.ReportProgress(i, Message);
                        continue;
                    }
                }
                //}
                //catch
                //{
                //    //记录日志

                //    continue;
                //}
                //finally
                //{
                //}
            }

            #endregion foreach

            ALLlistCon.Remove(ConnectionID);
            OverlistCon.Remove(ConnectionID);
            TdxApi.TdxHq_Multi_Disconnect(ConnectionID);
            //IsFinanceWork = false;
        }
    }
}